package cn.wolfcode.crm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeRoleMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.mapper.RolePermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
@Service
public class RoleServiceImpl implements IRoleService{

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private RolePermissionMapper rolePermissionMapper;
	
	@Autowired
	private EmployeeRoleMapper employeeRoleMapper;

	@Override
	public void saveOrUpdate(Role entity) {
		if (entity.getId() == null) {
			roleMapper.insert(entity);
			if (entity.getIds() != null && entity.getIds().length > 0) {
				rolePermissionMapper.insertRolePermission(entity.getId(), entity.getIds());
			}
		}else {
			roleMapper.update(entity);
			rolePermissionMapper.removeByRoleId(entity.getId());
			if (entity.getIds() != null && entity.getIds().length > 0) {
				rolePermissionMapper.insertRolePermission(entity.getId(), entity.getIds());
			}
		}
		
	}

	@Override
	public Role get(Long id) {
		return roleMapper.selectPermissionsByRoleId(id);
	}

	@Override
	public PageInfo<Role> list(QueryObject qo) { 
		PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
		List<Role> list = roleMapper.selectAll(qo);
		return new PageInfo<>(list);
	}

	@Override
	public List<Role> listNotPage(QueryObject qo) {
		List<Role> list = roleMapper.selectAll(qo);
		return list;
	}

	@Override
	public String delete(Long id) {
		String message;
		//根据roleId查询employee与role关系
		long count = employeeRoleMapper.countEmployeeRoleByRoleId(id);
		if (count > 0) {
			message = "删除失败，角色有被用户关联，不能删除";
		}else {
			rolePermissionMapper.removeByRoleId(id);
			roleMapper.delete(id);
			message = "删除成功";
		}
		return message;
	}

}
